<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-form :inline="true" ref="searchForm" :model="searchObj" :rules="searchRules" label-width="80px">
        <el-form-item label="人员编号" prop="employeeNo">
          <el-input placeholder="请输入" v-model.trim="searchObj.employeeNo" @keyup.enter.native='doSearch()'>
          </el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="employeeName">
          <el-input placeholder="请输入" v-model.trim="searchObj.employeeName" @keyup.enter.native='doSearch()'>
          </el-input>
        </el-form-item>
        <el-form-item label="雇佣性质" prop="empType">
          <el-select v-model="searchObj.empType" placeholder="请选择">
            <el-option v-for="item in employmentList" :key="item.key" :label="item.value" :value="item.key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input placeholder="请输入" v-model.trim="searchObj.phone" @keyup.enter.native='doSearch()'
>
          </el-input>
        </el-form-item>

        <el-form-item label="">
          <el-button type="primary" @click="doSearch">搜索</el-button>
          <el-button type="primary" @click="doReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-row>


    <el-row>
      <el-col :span="4">
        <div class="grid-content bg-purple">
          <el-tree
            :props="treeProps"
            :load="loadNode"
            lazy
            :expand-on-click-node="false"
            @node-click="nodeClick"
            >

          </el-tree>
        </div>
      </el-col>
      <el-col :span="20">
        <el-row class="mt-20 pl-10" type="flex" justify="start" :gutter="20">
          <el-button type="success" @click="showDialog(0)">新增</el-button>
          <el-button type="danger" :disabled="btnDisabled" @click="showComfirm()">批量删除</el-button>
          <el-button type="warning" @click="exportEmpAsync">导出</el-button>
        </el-row>
        <el-table class="mt-20" :data="list" v-loading.body="listLoading" element-loading-text="Loading" border fit highlight-current-row
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55">
          </el-table-column>
          <el-table-column prop="employeeNo" label="人员编号">
          </el-table-column>
          <el-table-column prop="employeeName" label="姓名">
          </el-table-column>
          <el-table-column prop="departmentName" label="部门">
          </el-table-column>
          <el-table-column prop="gender" label="性别">
            <template slot-scope="scope">
              <span>{{sexList.find(item=> item.key == scope.row.gender).value}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="employType" label="雇佣性质">
            <template slot-scope="scope">
              <span>{{employmentList.find(item=> item.key == scope.row.employType).value}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="phoneNum" label="手机号码">
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="text" size="small"><router-link :to="`/personnelFilesPrint/${scope.row.employeeId}`">打印</router-link></el-button>
              <el-button type="text" size="small" @click="showDialog(scope.row.employeeId)">编辑</el-button>
              <el-button type="text" size="small" @click="showComfirm(scope.row.employeeId)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row class="mt-20" type="flex" justify="center">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="pageSizes"
            :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
          </el-pagination>
        </el-row>
      </el-col>
    </el-row>

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input type="textarea" :rows="2" v-model="form.content"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrEdit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {
    findAllEmployee,exportEmp,deleteEmployee,findEmpParentDept,findEmpChildrenDept,
  } from "@/api/departPersonManage/personnelFiles";

  import {
    employmentList,sexList
  } from "@/constants/code";
  import {
    deleteConfirm
  } from "@/utils/deleteConfirm";
  import {
    requireInput,requireInputWithMaxLengthN,phoneNumInputN
  } from "@/utils/validateForm";
  import tableToExcel from '@/utils/exportExcel';


  export default {
    data() {

      return {
        treeProps: {
          label: 'departmentName',
          children: 'zones',
          isLeaf: 'leaf'
        },
        searchObj: {
          employeeNo: "",
          phone: "",
          employeeName: "",
          empType: "",
        },
        searchRules: {
          employeeNo: requireInputWithMaxLengthN(),
          employeeName: requireInputWithMaxLengthN(),
          phone: [...phoneNumInputN,...requireInputWithMaxLengthN()],
        },
        exportObj: {},
        list: [],
        listLoading: false,
        currentPage: 1,
        total: 0,
        pageSize: 5,
        pageSizes: [5, 10],
        btnDisabled: true,
        multipleSelection: [],
        dialogVisible: false,
        dialogTitle: "新增",
        form: {
          title: "",
          content: ""
        },
        rules: {
          title: requireInput("请输入标题"),
          content: requireInput("请输入内容")
        },
        sexList,
        employmentList,
        currentId: 0,
        departmentId: ''
      };
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: "success",
          draft: "gray",
          deleted: "danger"
        };
        return statusMap[status];
      }
    },
    created() {

      this.findAllEmployeeAsync();
    },
    methods: {
      doSearch() {
        this.exportObj = this.searchObj;
        this.$refs.searchForm.validate(vaild=> {
          if(vaild) {
            this.findAllEmployeeAsync()
          }
        })

      },

      doReset() {
        this.$refs.searchForm.resetFields(); //对整个表单进行重置
        this.findAllEmployeeAsync();
      },

      showDialog(id) {
        this.$router.push(`/personnelFilesDialog/${id}`)
      },

      doExport(data) {
        let thead = ['人员编号','姓名','部门','性别','雇佣性质','手机号码'];
        let list = data.map(item=> {
          return {
            employeeNo: item.employeeNo,
            employeeName: item.employeeName,
            departmentName: item.departmentName,
            gender: sexList.find(i=>i.key==item.gender).value,
            employType: employmentList.find(i=>i.key==item.employType).value,
            phoneNum: item.phoneNum,
          }
        })
        tableToExcel(list,thead);
      },

      nodeClick(data) {
        this.departmentId = data.departmentId;
        this.findAllEmployeeAsync();
      },

      addOrEdit() {
        if (this.dialogTitle == "新增") {
          //this.toinsertAsync()
        } else {
          //this.toupdateAsync()
        }

        this.dialogVisible = false;
      },

      handleClose() {
        this.dialogVisible = false;
        this.form = {
          title: "",
          content: ""
        };
      },

      doDelete() {
        let ids = ''
        if(this.currentId) {
          ids = this.currentId;
        }else {
          ids = this.multipleSelection.map(item => item.employeeId).join(',');
        }
        this.deleteEmployeeAsync(ids)
      },

      handleSizeChange(val) {
        this.pageSize = val;
        this.findAllEmployeeAsync();
      },

      handleCurrentChange(val) {
        this.currentPage = val;
        this.findAllEmployeeAsync();
      },

      showComfirm(id = null) {
        this.currentId = id
        deleteConfirm(this, this.doDelete, this.findAllEmployeeAsync);
      },

      handleSelectionChange(val) {
        this.multipleSelection = val;
        this.btnDisabled = this.multipleSelection.length < 1;
      },

      async findAllEmployeeAsync() {
        let {code,data,msg} = await findAllEmployee({
          departmentId: this.departmentId,
          ...this.searchObj,
        },{
          page: this.currentPage,
          pageSize: this.pageSize
        })
        if(code=='00000') {
          this.list = data.rows;
          this.total = data.total;
        }
      },

      async deleteEmployeeAsync(ids) {
        let {code,data,msg} = await deleteEmployee({
          empIds: ids
        });
        if(code=='00000') {
          this.findAllEmployeeAsync();
        }
      },

      async loadNode(node, resolve) {

        if (node.level === 0) {
          let {code,data,msg} = await findEmpParentDept();
          if(code == '00000') {
            this.treeProps = {
              label: 'departmentName',
              children: 'zones',
              isLeaf: 'leaf'
            };
            return resolve(data);
          }

        }

        let {code,data,msg} = await findEmpChildrenDept({
          departmentId: node.data.departmentId
        });
        resolve(data);

      },

      async exportEmpAsync() {
        let {code,data,msg} = await exportEmp(this.exportObj)
        if(code=='00000') {
          this.doExport(data);
        }
      }
    }
  };

</script>
